﻿using System;
using System.ComponentModel;

namespace MvvmFx.Common.ViewModels.Behaviors.Validation
{
    ///<summary>
    /// ValidationRules class is designed to provide support 
    /// to validate rules applied against properties of the 
    /// ViewModel object. 
    ///</summary>
    public partial class ValidationService
    {
        private bool _throwExceptionsOnBrokenRule;

        /// <summary>
        /// Gets or sets the value of the <see cref="ThrowExceptionsOnBrokenRule"/> property.
        /// </summary>
        public bool ThrowExceptionsOnBrokenRule
        {
            get { return _throwExceptionsOnBrokenRule; }
            set
            {
                if (_throwExceptionsOnBrokenRule != value)
                {
                    _throwExceptionsOnBrokenRule = value;
                }
            }
        }


        /// <summary>
        /// Event handler for the PropertyChanged event of the ViewModel
        /// object being tracked. This marks the ChangeService as being
        /// modified, and maintains hooks to a trackable child object if
        /// the TrackingMode is TrackChildren.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var propertyNames = ValidationRules.CheckRules(e.PropertyName);
            foreach (var name in propertyNames)
            {
                // OnPropertyChanged(name);
                ValidationRules.CheckRules(name);
            }

            //Check if the broken rule should be thrown as an exception.
            //
            if (!_throwExceptionsOnBrokenRule)
            {
                return;
            }
            
            
            string ruleDescription = this[e.PropertyName];
            if (!string.IsNullOrEmpty(ruleDescription))
            {
                //We have to throw an exception for Silverlight
                //
                throw new ValidationException(ruleDescription);
            }
        }
    }
}
